﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PropertyManagementSystemAPI.Authodtion;
using PropertyManagementSystemAPI.Common.RedisHelper;
using PropertyManagementSystemAPI.Common.WeChatHelper;
using PropertyManagementSystemAPI.Models;
using StackExchange.Redis;
using System.Collections.Generic;
using static Mysqlx.Expect.Open.Types.Condition.Types;

namespace PropertyManagementSystemAPI.Controllers
{
    /// <summary>
    /// 登录管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("any")]
    [ApiExplorerSettings(GroupName = "登录控制器")]
    [Authorize]
    public class LoginController : ControllerBase
    {
        static IAuthenticateService authService;
        IFreeSql db;
        public readonly IDatabase rediusDB;
        public LoginController(IAuthenticateService _authService, IFreeSql _db, RedisBase _rediusDB)
        {
            db = _db;
            authService = _authService;
            rediusDB = _rediusDB.GetDatabase();
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="l">用户名和密码</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public IActionResult Login([FromBody] Common.Login l)
        {
            Models.Systeminfo list = db.Select<Models.Systeminfo>()
                .Where(x => x.Sysname == l.sysname && x.Syspassword == l.syspwd)
                .First();
            if (list != null)
            {
                //登录成功
                string token;
                if (authService.IsAuthenticated(list, out token))
                {
                    //存储登录信息到redius中
                    rediusDB.StringSet("sysLoginInfo", JsonConvert.SerializeObject(list));
                    return Ok(token);
                }
                else
                {
                    return Ok(1);
                }
            }
            else
            {
                //登录失败
                return Ok(0);
            }
        }


        /// <summary>
        /// 微信小程序登录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("getLoginByWXXCX")]
        [AllowAnonymous]
        public IActionResult getLoginByWXXCX([FromBody] Common.Login info)
        {
            Ownerinfo ownerinfo = db.Select<Models.Ownerinfo>().Where(a => a.Ologincode == info.sysname && a.Password == info.syspwd).First();
            int code = 210;
            string msg = string.Empty;
            string token = string.Empty;
            if (ownerinfo != null)
            {
                if (authService.IsAuthenticated(ownerinfo, out token))
                {
                    //登录成功
                    code = 200;
                    msg = "登录成功";

                }
                else
                {
                    code = 210;
                    msg = "登录失败";
                }
            }
            else
            {
                msg = "登录失败";
            }
            var json = new { code = code, msg = msg, token = token, id = ownerinfo.Oid };
            return Ok(json);
        }

        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <param name="id">当前登录用户id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult getSessionInfo(int id)
        {
            var list = db.Select<Models.Ownerinfo, Models.Houseinfo>()
                .LeftJoin((a, b) => a.Hid == b.Hid)
                .Where((a, b) => a.Oid == id && a.Isdelete == false && b.IsDelete == false)
                .First((a, b) => new { a.Oid, a.Oidcard, a.Obirthday, a.Orealname, a.Ophone, a.Osex, a.Hid, a.Ologincode, a.Oimg, b.Hname });

            return Ok(list);
        }

        /// <summary>
        /// 获取微信小程序token
        /// </summary>
        /// <param name="code">小程序code码</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("getToken")]
        public string getToken(string code)
        {
            string result = "";
            if (!string.IsNullOrEmpty(code))
            {
                string getTokenUrl = WeChat_Config.token_url + "appid=" + WeChat_Config.wx_appid + "&secret=" + WeChat_Config.wx_select + "&js_code=" + code + "&grant_type=authorization_code";
                string tokenResult = WeChat_Config.HttpGet(getTokenUrl);//获取微信token

                //获取getAccessToken接口凭证
                string AccessTokenUrl = WeChat_Config.getAccessToken_url + $"grant_type=client_credential&appid={WeChat_Config.wx_appid}&secret={WeChat_Config.wx_select}";
                string AccessTokenResult = WeChat_Config.HttpGet(AccessTokenUrl);
                rediusDB.StringSet("AccessToken", AccessTokenResult);
                rediusDB.KeyExpire("AccessToken", TimeSpan.FromHours(1));//设置10s后过期

                result = tokenResult;
            }
            else
            {
                //用户禁止授权
                result = "0";
            }
            return result;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        //[AllowAnonymous]
        //[HttpGet]
        //[Route("getAccessToken")]
        //public string getAccessToken()
        //{
        //    //拼接获取用户信息的接口，通过access_token调用接口（获取用户个人信息接口（/sns/userinfo））
        //    string UserInfoUrl = WeChat_Config.getAccessToken_url + $"?grant_type=client_credential&appid={WeChat_Config.wx_appid}&secret={WeChat_Config.wx_select}";
        //    string userInfoResult = WeChat_Config.HttpGet(UserInfoUrl);
        //    return userInfoResult;
        //}


        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("GetUserInfo")]
        public string GetUserInfo(string openid)
        {
            //string AccessTokenResult = rediusDB.StringGet("AccessToken");

            //Token_Result res = JsonConvert.DeserializeObject<Token_Result>(AccessTokenResult);
            string str = "78_OacbSCURvR8jFZmNqa4263u7_b4xb92wNDl3lDZct6J-CVVp66ywezW9OqPO3y8ivSE0jVpKA6HAL5me65da78bXuT0DicN-sWEidWOEpAnh7sCn1lOBoskGdZ4CTNhAEARIC";

            //拼接获取用户信息的接口，通过access_token调用接口（获取用户个人信息接口（/sns/userinfo））
            string UserInfoUrl = WeChat_Config.userinfo_url + "access_token=" + str + "&openid=" + openid;
            string userInfoResult = WeChat_Config.HttpGet(UserInfoUrl);
            // 反序列化用户信息
            //UserInfo_Result uobj = JsonConvert.DeserializeObject<UserInfo_Result>(userInfoResult);
            /*
             * 此处可做 用户信息 相关逻辑操作
             */
            return userInfoResult;
        }

    }
}
